今天要設計每一頁的NavigationBar:
我們直接在BaseViewController底下做就可以了,因為我們每一個畫面都會去繼承BaseViewController:
public func setupNavigationBarStyle(backgroundColor: UIColor,
tintColor: UIColor = .white,
foregroundColor: UIColor = .white) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = backgroundColor
self.navigationController?.navigationBar.tintColor = tintColor
appearance.titleTextAttributes = [
NSAttributedString.Key.foregroundColor : foregroundColor
]
self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
self.navigationItem.title = title
}
然後在BaseViewController 的viewDidLoad加入這段:
override func viewDidLoad() {
super.viewDidLoad()
self.setupNavigationBarStyle(backgroundColor: .black)
}
因為我會希望讓標頭在左邊,所以需要自己建立一個Label在上面,程式碼如下:
let lbNavTitle = UILabel (frame: CGRect(x: 20, y: 10, width: 320, height: 120))
lbNavTitle.center = CGPoint(x: 50, y: 0)
lbNavTitle.text = CustomTabBar.items[index].title
lbNavTitle.font = UIFont.systemFont(ofSize: 20)
lbNavTitle.backgroundColor = UIColor.black
lbNavTitle.textColor = UIColor.lightGray
lbNavTitle.numberOfLines = 0
lbNavTitle.textAlignment = .left
或是你可以用這種方式:
let label = UILabel()
label.textColor = UIColor.lightGray
label.text = "消息中心"
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: label)